package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * projectName: wokepase1
 *
 * @author: 强力
 * time: 2021/10/18 16:53
 * description:扣费策略
 */
@Service(value = "fee")
@Slf4j
public class FeeServiceImpl implements FilerChainService{
    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        log.info("[扣费策略模块]扣费策略开始执行,StandardSubmit={}",standardSubmit);
        //1.查询当前用户账号余额信息
        Map clientMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID());
        if (clientMap == null) {
            log.info("[扣费策略模块]获取用户信息失败,StandardSubmit={}",standardSubmit);
            return false;
        }
        Object feeObj = clientMap.get("fee");
        if (StringUtils.isEmpty(feeObj)) {
            log.info("[扣费策略模块]获取用户信息失败,StandardSubmit={}",standardSubmit);
            return false;
        }
            //账户总余额
        long totalFee = Long.parseLong(String.valueOf(feeObj));

        // 2.查询当前这一条短信需要的费用
        Long fee = standardSubmit.getFee();
        //3.判断用户,剩余费用 >=发送这条短信需要的费用
        if (fee <= totalFee){
            //4.如果满足扣费要求,开始扣费,获得扣完费用后的总余额
            totalFee = cacheFeign.hincr(CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID(), "fee", -fee);

        //5.判断扣费完成后,用户剩余的金额 是否 <0
         if (totalFee<0){
             //6.如果扣除后用户余额 <0,用户余额不足,将扣除费用返还,发送失败且发送日志
                //推送发送失败信息到mq中,interface接口项目将这个数据接收后返回给用户方项目
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
                //记录发送失败日志到mq中,search搜索项目,将这个数据写入到ES服务器供客户管理员在短信管理平台中查询使用
             pushMsgUtil.sendLog(standardSubmit,StrategyConstants.STRATEGY_ERROR_FEE);
             log.info("[扣费策略模块]扣费失败,余额不足,StandardSubmit={}",standardSubmit);
             return false;
    }
        //7.如果成功,计算客户总余额到redis中
            cacheFeign.incr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE+standardSubmit.getClientID(),-fee);
            log.info("[扣费策略模块]扣费成功,StandardSubmit={}",standardSubmit);
            return true;
        }else {
            //推送发送失败信息到mq中,interface接口项目将这个数据接收后返回给用户方项目
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
            //记录发送失败日志到mq中,search搜索项目,将这个数据写入到ES服务器供客户管理员在短信管理平台中查询使用
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_FEE);
            log.info("[扣费策略模块]扣费失败,余额不足,StandardSubmit={}", standardSubmit);
            return false;
        }
    }
}
